$(document).ready(
	function(){ 
		$('#consoleDlg')[0].style.display = "none";
		
		//$('#roleMenuForm').hide();
		$("#roleMenuDiv")[0].style.display = "none";
		
		$("#gridTable").jqGrid({   
            url:getContextPath()+"/authority/roles/getAllRoles.do",   
            datatype: "json",// "local",
            height: 170,   
            colNames:['序号','角色名称','角色描述'],
			colModel:[
				{name:'id', index:'id', width:0, align:"left", hidden:true},
		   		{name:'name', index:'name', width:100, align:"left"},
		   		{name:'description', index:'description', width:250, align:"left", sortable:false}
			],
            sortname:'id',   
            // sortorder:'asc',
            viewrecords:true, 
            pgtext : "页 {0} 共 {1}页",
            recordtext:'记录 {0} - {1} 总记录数 {2}',  
            emptyrecords : "无数据",
            loadtext : "获取数据中...",
            rowNum: 8,//10,   
            loadonce: true,
            //rowList:[10,20,30],   
            jsonReader: { 
				repeatitems:false,   	 // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
				root: "rows",               // 数据行（默认为：rows）   
				total: "total",        // 总记录数   
				page: "page",            // 当前页   
				records: "records"
                //root:"dataRows",        // 数据行（默认为：rows）
                //page: "pages",    // 当前页
                //total: "totals",  // 总页数
                //records: "records",  // 总记录数
                //repeatitems : false    
            }, 
            //prmNames : {
				//search : "search",
				//rows:"pageModel.rows",
				//page:"pageModel.page",
				// sort:"page.orderBy",
				// order:"page.order"
			//}, 
            pager:"#gridPager",  
            caption: "角色信息 "
		});  
		$("#gridTable").jqGrid('navGrid','#gridPager',{edit:false,add:false,del:false});
		
		// 配置对话框
		$("#consoleDlg").dialog( {
			autoOpen : false,
			modal : true, // 设置对话框为模态（modal）对话框
			resizable : true,
			width : 480,
			buttons : { // 为对话框添加按钮
				"取消" : function() {
					$("#consoleDlg").dialog("close")
				},
				"添加" : addRoleInfo,
				"保存" : updateRoleInfo,
				"删除" : deleteRoleInfo
			}
		});  
		
		$("#roleMenuDiv").dialog( {
			autoOpen : false,
			modal : true, // 设置对话框为模态（modal）对话框
			resizable : true,
			width : 600,
		});  
	}
)

		// getContextPath
		function getContextPath() {
    		var pathName = document.location.pathname;
    		var index = pathName.substr(1).indexOf("/");
    		var result = pathName.substr(0,index+1);
    		return result;
		};

		var openDialog4Adding = function() {  
			var consoleDlg = $("#consoleDlg");  
			var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");  
			consoleDlg.find("input").removeAttr("disabled").val("");  
			consoleDlg.find("#eDescription").val("");
			consoleDlg.find("textarea").removeAttr("disabled");
			dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
			dialogButtonPanel.find("button:contains('添加')").show();  
			consoleDlg.dialog("option", "title", "添加角色 ").dialog("open");  
		};  
		
		var openDialog4Updating = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");    
	        consoleDlg.find("input").removeAttr("disabled"); 
	        consoleDlg.find("textarea").removeAttr("disabled");
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('保存')").show();  
	        consoleDlg.dialog("option", "title", "修改角色");  
	          
	        loadSelectedRowData();  
		};
		
		var openDialog4Deleting = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");         
	        consoleDlg.find("input").attr("disabled", true); 
	        consoleDlg.find("textarea").attr("disabled", true); 
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('删除')").show();  
	        consoleDlg.dialog("option", "title", "删除角色");  
	          
	        loadSelectedRowData();  
		};
		
		var loadSelectedRowData = function() {
			var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow");
	    	//alert("selectRowID:"+selectedRowId);
	    	if (!selectedRowId) {
	    		alert("请先选择需要编辑的行!");
	    		return false;
	    	} else {
	    		var params = {"eid" : selectedRowId};
	    		// 从Server读取对应ID的JSON数据
	    		$.ajax( {
	    			type:"POST",   
	    			url : getContextPath()+"/authority/roles/getRoleByID.do",
	    			data : params,
	    			dataType : "json",
	    			//contentType: "application/json",
	    			cache : false,
	    			async:false,
	    			error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus.responseText);
					},
					success : function(data, textStatus) {
						// 如果读取结果成功，则将信息载入到对话框中     
						var rowData = data;
						var consoleDlg = $("#consoleDlg");

						consoleDlg.find("#selectId").val(rowData.id);
						//alert("hiddenID1:"+consoleDlg.find("#selectId").val());
						consoleDlg.find("#eName").val(rowData.name);
						consoleDlg.find("#eDescription").val(rowData.description);
						
						// 根据新载入的数据将表格中的对应数据行一并更新一下
						var dataRow = {
								id : rowData.id, // 从Server端得到系统分配的id  
								name : rowData.name,
								description : rowData.description
						};

						$("#gridTable").jqGrid("setRowData", data.id, dataRow);

						// 打开对话框
						consoleDlg.dialog("open");
					}
	    		});
	    	}
		};
		
		var checkValid = function() {
	    	var consoleDlg = $("#consoleDlg");
	    	var eName = $.trim(consoleDlg.find("#eName").val());
	    	if (eName=="") {
	    		alert("'角色名称'为必填信息");
	    		return false;
	    	}
		}
		
		var addRoleInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
			
			var eName = $.trim(consoleDlg.find("#eName").val());
			var eDescription = $.trim(consoleDlg.find("#eDescription").val());

			var params = {
					"eName" : eName,
					"eDescription" : eDescription
			};

			var actionUrl = getContextPath()+"/authority/roles/addRole.do";

			$.ajax( {
					type: "POST",
					url : actionUrl,
					data : params,
					dataType : "json",
					cache : false,
					error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus);
					},
					success : function(data, textStatus) {
						if (data != null) {
							var dataRow = {
									id : data.id, // 从Server端得到系统分配的id  
									name : data.name,
									description : data.description								
							};

							var srcrowid = $("#gridTable").jqGrid("getGridParam",
									"selrow");

							if (srcrowid) {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "before",
										srcrowid);

							} else {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "first");
							}
							consoleDlg.dialog("close");

							alert("角色添加操作成功!");

						} else {
							alert("角色名称重复，添加操作失败!");
						}
					}
				});  
		};
		
		var updateRoleInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
			
			var eID = $.trim(consoleDlg.find("#selectId").val()); 
			var eName = $.trim(consoleDlg.find("#eName").val());
			var eDescription = $.trim(consoleDlg.find("#eDescription").val());

			var params = {
					"eID" : eID,
					"eName" : eName,
					"eDescription" : eDescription
			};

			var actionUrl = getContextPath()+"/authority/roles/updateRole.do";

			$.ajax( {
				type : "POST",
				url : actionUrl,
				data : params,
				dataType : "json",
				cache : false,
				error : function(textStatus, errorThrown) {
					alert("系统ajax交互错误: " + textStatus);
				},
				success : function(data, textStatus) {
					if (data != null) {
						var dataRow = {
								id : data.id, // 从Server端得到系统分配的id  
								name : data.name,
								description : data.description	
						};
						alert("角色更新成功!");
						consoleDlg.dialog("close");
						$("#gridTable").jqGrid("setRowData", data.id, dataRow);
					} else {
						alert("角色名称重复，修改操作失败!");
					}
				}
			});
		};
		
		var deleteRoleInfo = function() {
			var consoleDlg = $("#consoleDlg");  
			
			var r=confirm("确认要删除该角色吗？删除时会将菜单关联一并删除");
			if (r==false) {
				consoleDlg.dialog("close"); 
				return false;
			}
	        
	        var pId = $.trim(consoleDlg.find("#selectId").val());  
	        var params = {"eID" : pId};  
	        var actionUrl = getContextPath() + "/authority/roles/deleteRole.do";
	        $.ajax({  
	        	type : "POST",
	            url : actionUrl,  
	            data : params,  
	            //dataType : "json",  
	            cache : false,  
	            error : function(textStatus, errorThrown) {  
	                alert("系统ajax交互错误: " + textStatus);  
	            },  
	            success : function(data, textStatus) {  
	                if (data == "success") {  
	                    $("#gridTable").jqGrid("delRowData", pId);  
	                    consoleDlg.dialog("close");  
	                    alert("角色删除成功!");  
	                } else {  
	                    alert("删除操作失败!");  
	                }  
	            }  
	        });  
		};
		
		var showRoleMenuDef = function() {
			var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow");
	    	//alert("selectRowID:"+selectedRowId);
	    	if (!selectedRowId) {
	    		alert("请先选择需要编辑的行!");
	    		return false;
	    	}
			var mapDlg = $("#roleMenuDiv"); 
	        mapDlg.find("input").removeAttr("checked");
			//mapDlg.find("input").attr("checked",true);
	        mapDlg.dialog("option", "title", "角色功能授权");
	        //根据ajax结果初始化所有的checkbox
	        var params = {"eID" : selectedRowId};
	        var actionUrl = getContextPath() + "/authority/roles/getRoleMenus.do";
	        $.ajax({
	        	type : "POST",
	            url : actionUrl,  
	            data : params, 
	            dataType : "json",  
	            cache : false,  
	            error : function(textStatus, errorThrown) {  
	                alert("系统ajax交互错误: " + textStatus);  
	            },  
	            success : function(data, textStatus) {  
	            	if (data != null) {
						for (var i=0; i<data.length; i++) {
							for (var j=0; j<data[i].children.length; j++) {
								$("input[type=\"checkbox\"][value=\""+data[i].children[j].id+"\"]").attr("checked",true);
							}
						}
					}
	            }
	        });
	        
			mapDlg.dialog("open");  
			
		};
		
		var setRoleMenuMap = function() {
			//添加菜单关联
			//得到选中的集合
			//var selIDs = new Array();
			var selIDs = "";
			var selitems = $("input[type=\"checkbox\"]:checked").each(function(){
				//selIDs.push($(this).val());
				selIDs += $(this).val() + ",";
			});
			//alert(selIDs);
			var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow");
			var params = {"roleID" : selectedRowId , "menuIDs" : selIDs};
			//var params = {"roleID" : selectedRowId , "menuIDs" : ["111","222"]};
			var actionUrl = getContextPath() + "/authority/roles/setRoleMenus.do";
			$.ajax({
	        	type : "POST",
	            url : actionUrl,  
	            data : params, 
	            //dataType : "json",  
	            cache : false,  
	            error : function(textStatus, errorThrown) {  
	                alert("系统ajax交互错误: " + textStatus);  
	            },  
	            success : function(data, textStatus) {  
	            	if (data == "success") {  
	            		$("#roleMenuDiv").dialog("close");  
	                    alert("角色权限授权成功!");  
	                } else {  
	                    alert("角色权限授权失败!");  
	                }  
	            }
	        });
			
		};
		
		var closeRoleMenuDef = function() {
			$("#roleMenuDiv").dialog("close")
		};
		
		var selectAllMenus = function() {
			$("#roleMenuDiv").find("input").attr("checked",true);
		};